/* 
 *
 */
package com.cory.api.core;

import java.util.UUID;
import com.cory.api.config.ApiConfig;
import com.cory.api.domain.ApiPrincipal;
import com.cory.boot.component.cache.RedisUtils;
import com.cory.boot.utils.SpringUtils;

/**
 * 签名缓存
 * @author xiongcong
 * @date 2020-04-20
 */
public class ApiTokenCache {
    
    private static final int expireSeconds = 60 * 60 * 24;
    private static ApiConfig config = SpringUtils.getBean(ApiConfig.class);
    
    public static String createPrincipal(ApiPrincipal principal) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        principal.setToken(token);
        RedisUtils.setObj(config.getCachePrefix() + ":token:" + token, principal, expireSeconds);
        return token;
    }
    
    public static void updatePrincipal(ApiPrincipal principal) {
        RedisUtils.setObj(config.getCachePrefix() + ":token:" + principal.getToken(), principal, expireSeconds);
    }
    
    public static ApiPrincipal getPrincipal(String token) {
        return RedisUtils.getObj(config.getCachePrefix() + ":token:" + token, ApiPrincipal.class);
    }
    
    public static void setCache(String token, String key, String value) {
        setCache(token, key, value, expireSeconds);
    }
    
    public static void setCache(String token, String key, String value, int expireSeconds) {
        RedisUtils.set(config.getCachePrefix() + ":" + token + ":" + key, value, expireSeconds);
    }
    
    public static String getCache(String token, String key) {
        return RedisUtils.get(config.getCachePrefix() + ":" + token + ":" + key);
    }
}
